package com.chat.provider.rpc;

import com.alibaba.fastjson.JSON;
import com.chat.provider.invoke.SpringBeanContent;
import com.chat.server.base.InvokeModel;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Auther created by haoteng on 2019/08/16
 */
public class DemoServerInChannelHandler extends ChannelInboundHandlerAdapter {

    Logger log = LoggerFactory.getLogger(DemoServerInChannelHandler.class);


    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object s) throws Exception {
        ByteBuf in = (ByteBuf) s;
        String info = in.toString(CharsetUtil.UTF_8);
        log.info("服务器收到信息:" + info);
        InvokeModel invokeModel = JSON.parseObject(info, InvokeModel.class);
        Object o = SpringBeanContent.invoke(invokeModel);

        ByteBuf content = Unpooled.buffer().writeBytes(JSON.toJSONString(o).getBytes());
        channelHandlerContext.writeAndFlush(content);
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        log.info("服务器收到客户端连接信息 : " + ctx.channel().remoteAddress() + "!");
//        ctx.channel().writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName() + " service!");
        super.channelActive(ctx);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(ChannelFutureListener.CLOSE);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("服务器收到客户端断开连接信息");
        super.channelInactive(ctx);
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        log.info("注册信息");
        ctx.fireChannelRegistered();
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        log.info("取消注册信息");
        ctx.fireChannelUnregistered();
    }
}
